// pages/login/index.js
import Toast from '@vant/weapp/toast/toast';
import common from '../../common/compents.js';
let App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginState: false,
    phone: "",
    code: "",
    phoneLength:false,
    codeLength:0,
    first: true,
    showTime: false,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: false
  },
  // 方法
  phoneInput(e) {
    // console.log(e);
    let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    let _status;
    if(!myreg.test(e.detail.value)){
      _status = false;
    }else{
      _status = true;
    }
    this.setData({
      phone: e.detail.value,
      phoneLength:_status
    })
  },
  codeInput(e) {
    // console.log(e);
    this.setData({
      code: e.detail.value,
      codeLength:e.detail.value.trim().length
    })

  },
  // 倒计时结束
  finished() {
    this.setData({
      showTime: false
    })
  },
  // 获取验证码
  getCode() {
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(this.data.phone)) {
      Toast('手机号码格式不正确');
      return false;
    }
    this.setData({
      first: false,
      showTime: true
    })
    wx.nextTick(() => {
      const countDown = this.selectComponent('.control-count-down');
      countDown.start();
    })
    this.sendCode();
  },
  sendCode() {
    let that = this;
    wx.request({
      url: App.globalData.testApi + '/wechat/common/captcha/sms',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        mobile: that.data.phone,
        type: "login"
      },
      success(resapi) {
        if (resapi.data.code == 0) {
          Toast("发送成功！")
        } else if (resapi.data.code == 2024){
          Toast("抱歉，你的手机号尚未注册博道数据！")
        }else{
          Toast(resapi.data.message);
        }
      },
      fail(resapi) {
        console.log('失败', resapi);
        Toast("网络请求失败！");
      }
    })
  },
  // 重新发送验证码
  returnGetCode() {
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(this.data.phone)) {
      Toast('手机号码格式不正确');
      return false;
    }
    this.setData({
      showTime: true
    })
    const countDown = this.selectComponent('.control-count-down');
    countDown.reset();
    countDown.start();
    this.sendCode();
  },
  // 点击登录
  login() {
    if (this.data.phone.trim().length == 0) {
      Toast('请输入手机号码');
      return false;
    }
    var myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!myreg.test(this.data.phone)) {
      Toast('手机号码格式不正确');
      return false;
    }
    if (this.data.code.trim().length == 0) {
      Toast('请输入验证码');
      return false;
    }
    // 登录
    let that = this;
    wx.showLoading({
      mask: true,
    })
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: App.globalData.testApi + '/wechat/passport/login',
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {
            code: res.code,
            mobile: that.data.phone,
            sms_code: that.data.code
          },
          success(resapi) {
            if (resapi.data.code == 0) {
              wx.setStorageSync('token', resapi.data.data.token);
              common.getInit(resapi.data.data.token,'login');
              Toast("登录成功，即将进入首页！");
            } else {
              Toast(resapi.data.message)
            }
          },
          fail(resapi) {
            console.log('失败', resapi);
            Toast("网络请求失败！");
          },
          complete(resapi){
            wx.hideLoading();
          }
        })
      },
      fail: res => {

      }
    })
  },
  // 微信授权回调函数
  bindGetUserInfo(e){
    // console.log(e)
    if (e.detail.userInfo) {
      // console.log(11,e.detail)
      wx.setStorageSync('userInfo', JSON.stringify(e.detail.userInfo));
      this.login();
    }else{
      Toast("授权登录失败，请重新进行微信授权！")
    }
  },
  goToIndex() {
    wx.redirectTo({
      url: "/pages/index/index"
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(wx.getUserProfile)
    let that = this;
    if (wx.getStorageSync("token")) {
      this.setData({
        loginState: false
      })
    } else {
      // wx.getUserProfile({
      //   desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      //   success: (res) => {
      //     console.log(res);
      //     wx.setStorageSync('userInfo', JSON.stringify(res.userInfo));
      //   },
      //   fail:(res)=>{
      //     console.log(res);
      //   }
      // })
      this.setData({
        loginState: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.hideLoading();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
})